package com.example.usermanager.controller;

import com.example.usermanager.model.UserInfo;
import com.example.usermanager.service.UserService;
import com.example.usermanager.util.ConstVariable;
import com.example.usermanager.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public boolean login(String loginname , String password , HttpServletRequest request){
        if(StringUtils.hasLength(loginname) && StringUtils.hasLength(password)){
            //参数有效不为空
            UserInfo userInfo = userService.getUserByLoginname(loginname);
            //UserInfo userInfo = userService.login(loginname, password);  密码明文
            if(userInfo != null && userInfo.getUid() > 0){
                //数据库中保存的加密的密码
                String dbPassword = userInfo.getPassword();
                if (PasswordUtil.decrypt(password , dbPassword)){
                    //查询成功
                    //将session存储
                    HttpSession session = request.getSession(true);
                    session.setAttribute(ConstVariable.USER_SESSION_KEY,userInfo);
                    return true;
                }
            }
        }
        return false;
    }

    //查询所有用户信息（无分页版）
    @RequestMapping("/list")
    public List<UserInfo> getAll(){
        return userService.getAll();
    }

    //根据分页得到用户信息
    @RequestMapping("/listbypage")
    public HashMap<String,Object> getListByPage(String username, String address, String email, Integer pindex, Integer psize) {
        HashMap<String,Object> result = new HashMap<>();
        if(pindex == null || pindex < 1){  //假设当前传入的参数无效或者没传，强制设置第一页
            pindex = 1;
        }
        if(psize == null || psize <= 0){  //假设当前传入的参数无效或者没传，强制设置第一页
            psize = 2;
        }
        if(!StringUtils.hasLength(username)){
            username = null;
        }
        if(!StringUtils.hasLength(address)){
            address = null;
        }
        if(!StringUtils.hasLength(email)){
            email = null;
        }
        int offset = (pindex - 1) * psize;
        List<UserInfo> list = userService.getListByPage(username, address, email, psize , offset);
        int totalCount = userService.getCountByPage(username, address, email);
        result.put("list" , list);
        result.put("count" , totalCount);
        return result;
    }

    //添加用户
    @RequestMapping("/add")
    public int add(UserInfo userInfo , HttpServletRequest request){
        int result = 0;
        //1、非空效验
        if(userInfo == null
           || !StringUtils.hasLength(userInfo.getUsername())
           || !StringUtils.hasLength(userInfo.getLoginname())
           || !StringUtils.hasLength(userInfo.getPassword())){
            return result;
        }

        //2、效验超级管理员身份
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null){
            return  result;
        }
        //当前用户已经存在
        UserInfo loginUser = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        //判断是否为管理员身份
        if(!loginUser.isIsadmin()){
            return result;
        }

        //3、效验登录名是否唯一
        UserInfo loginNameUser = userService.getUserByLoginname(userInfo.getLoginname());
        //表示查询到当前登录名的用户，不唯一不能插入
        if(loginNameUser != null && loginNameUser.getUid() > 0){
            return result;
        }

        //4、添加用户
        userInfo.setPassword(PasswordUtil.encrypt(userInfo.getPassword()));
        result = userService.add(userInfo);
        return result;
    }

    //根据id拿到用户信息
    @RequestMapping("/getuserbyuid")
    public UserInfo getUserByUid(Integer uid){
        UserInfo userInfo = null;
        //1、非空效验
        if(uid == null || uid <= 0){  //非法参数
            return userInfo;
        }
        //2、查询数据库
        userInfo = userService.getUserByUid(uid);
        //3、将密码隐藏
        userInfo.setPassword("");
        return userInfo;
    }

    //用户信息修改操作
    @RequestMapping("/update")
    public int updateUser(UserInfo userInfo , HttpServletRequest request){
        int result = 0;
        //1、非空效验
        if(userInfo == null || userInfo.getUid() <= 0
                || !StringUtils.hasLength(userInfo.getUsername())){
            return result;
        }

        //2、效验超级管理员身份
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null){
            return  result;
        }
        //当前用户已经存在
        UserInfo loginUser = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        //判断是否为管理员身份
        if(!loginUser.isIsadmin()){
            return result;
        }

        //3、更新用户信息
        if(StringUtils.hasLength(userInfo.getPassword())){
            userInfo.setPassword(PasswordUtil.encrypt(userInfo.getPassword()));
        }
        result = userService.updateUser(userInfo);
        return result;
    }

    //根据uid删除用户信息
    @RequestMapping("/del")
    public int delById(Integer uid){
        if(uid == null){
            return 0;
        }
        return userService.delById(uid);
    }

    //根据id删除
    @RequestMapping("/delbyids")
    public int delByIds(String ids , HttpServletRequest request){
        if(!StringUtils.hasLength(ids)){
            return 0;
        }
        String[] idsArr = ids.split(",");
        if(idsArr == null || idsArr.length <= 0){
            return 0;
        }

        //得到当前操作用户的id（为了避免删除的时候把自己删掉了）
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null){
            return 0;
        }
        int uid = ((UserInfo)session.getAttribute(ConstVariable.USER_SESSION_KEY)).getUid();
        //循环将字符串变成list
        List<Integer> idsList = new ArrayList<>();
        for(String item : idsArr){
            if(StringUtils.hasLength(item)){
                int thisUid = Integer.valueOf(item);
                //如果当前要删除的用户是正在操作的用户，直接返回
                if(thisUid == uid){
                    return 0;
                }
                idsList.add(thisUid);
            }
        }
        return userService.delByIds(idsList);
    }
}
